import React, { useCallback, useMemo } from 'react'
import { Button, Form, Input, Toast } from 'antd-mobile'
import request from '../utils/request'
import { Link, useNavigate } from 'react-router-dom'

function Login() {
    const navigate = useNavigate()
    const rules = useMemo(() => {
        return {
            username: [
                { required: true, message: '用户名不能为空' },
            ],
            password: [{ required: true, message: '密码不能为空' }]
        }
    }, [])
    const submit = useCallback(async (values) => {
        console.log('values', values)
        const { data } = await request.post('/login', values)
        if (data.code === 200) {
            Toast.show({
                content: '登录成功',
                position: 'top',
            })

            // 登录成功后，得到用户信息，并写入本地存
            localStorage.setItem('userInfo',JSON.stringify(data.data))

            navigate('/mine')
        }
    }, [])
    return <div>
        <Form
            layout='horizontal'
            footer={
                <>
                    <Button block type='submit' color='primary'>
                        登录
                    </Button>
                    <p>没有账户？去<Link to='/reg'>注册</Link></p>

                </>
            }
            onFinish={submit}
        >
            <Form.Header>用户注册</Form.Header>
            <Form.Item
                name='username'
                label='用户名'
                rules={rules.username}
                validateTrigger={['onChange', 'onBlur']}
            >
                <Input />
            </Form.Item>
            <Form.Item
                name='password'
                label='密码'
                rules={rules.password}
            >
                <Input type='password' />
            </Form.Item>
        </Form>
    </div>
}

export default Login;